"""
生成测试报告相关
"""
import os
import datetime
import subprocess
import zipfile
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header


from conf import settings
from utils.LogHandler import log
from utils.tools import Bar

class AllureOperator(object):

	def create_allure_report(self):
		""" 执行相关命令，生成测试报告 """
		log.info('正在执行生成allure报告命令')
		subprocess.call(settings.ALLURE_COMMAND, shell=True)  # ['allure', 'generate', 'xxx' '-o']
		# print(settings.ALLURE_COMMAND)
		log.info('生成allure报告成功')
		if settings.SEND_EMAIL:
			self.send_email()
		else:
			log.info('默认不发送邮件')

	def create_zip(self):
		""" 将测试报告打包 """
		start_zip_dir = settings.ALLURE_REPORT  # 要压缩文件夹的根路径
		# zip_file_name = settings.ZIP_FILE_NAME
		zip_file_path = settings.ALLURE_REPORT_ZIP_FILE_PATH
		f = zipfile.ZipFile(zip_file_path, 'w', zipfile.ZIP_DEFLATED)
		for dir_path, dir_name, file_names in os.walk(start_zip_dir):
			# 要是不replace，就从根目录开始复制
			file_path = dir_path.replace(start_zip_dir, '')
			# 实现当前文件夹以及包含的所有文件
			file_path = file_path and file_path + os.sep or ''
			for file_name in file_names:
				f.write(os.path.join(dir_path, file_name), file_path + file_name)


	def get_report_data(self):
		"""  读取压缩包"""
		with open(settings.ALLURE_REPORT_ZIP_FILE_PATH, 'rb') as f:
			return f.read()

	def send_email(self):
		""" 发送邮件 """
		# 打包测试报告
		self.create_zip()
		# 读取压缩包内容，准备发送
		report_datga = self.get_report_data()
		# 第三方 SMTP 服务
		mail_host = settings.EMAIL_HOST
		mail_user = settings.EMAIL_USER
		mail_pass = settings.EMAIL_TOKEN

		# 设置收件人和发件人
		sender = settings.EMAIL_SENDER
		receivers = settings.EMAIL_RECV_LIST  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
		# 创建一个带附件的实例对象
		message = MIMEMultipart()

		# 邮件主题、收件人、发件人
		subject = settings.EMAIL_SUBJECT  # 邮件主题
		message['Subject'] = Header(subject, 'utf-8')
		message['From'] = Header("{}".format(sender), 'utf-8')  # 发件人
		message['To'] = Header("{}".format(';'.join(receivers)), 'utf-8')  # 收件人

		# 邮件正文内容 html 形式邮件
		send_content = settings.EMAIL_CONTENT  # 获取测试报告
		text = MIMEText(send_content, 'plain', 'utf-8')  # 第一个参数为邮件内容

		# 构造附件
		att = MIMEText(_text=report_datga, _subtype='base64', _charset='utf-8')
		att["Content-Type"] = 'application/octet-stream'
		file_name = settings.ZIP_FILE_NAME   # 可以修改
		att["Content-Disposition"] = 'attachment; filename="{}"'.format(file_name)  # # filename 为邮件附件中显示什么名字
		message.attach(text)
		message.attach(att)

		try:
			smtp_obj = smtplib.SMTP()
			smtp_obj.connect(mail_host, 25)  # 25 为 SMTP 端口号
			smtp_obj.login(mail_user, mail_pass)
			smtp_obj.sendmail(sender, receivers, message.as_string())
			smtp_obj.quit()
			log.info("邮件发送成功")

		except smtplib.SMTPException:
			log.error("Error: 无法发送邮件")
		# 删除相关临时文件，包括，allure-result allure-report allure_report.zip
		Bar().rm([settings.ALLURE_REPORT_ZIP_FILE_PATH, settings.ALLURE_REPORT,settings.ALLURE_RESULT])


if __name__ == '__main__':
    AllureOperator().send_email()